import React, { Component, createRef } from 'react';

class Form extends Component {
  constructor() {
    super()
    this.myRef = createRef()
    this.fileRef = createRef()
  }

  state = {
    // value: null,
    value: 'abc',
    selectValue: ['0', '1'],
    checkboxValue: true,
    numValue: 8
  }

  handleTextareaChange = (e) => {
    this.setState({
      value: e.target.value
    })
  }

  handleSelectChange = (e) => {
    let value = e.target.value

    let index = this.state.selectValue.indexOf(value)

    if (index >= 0) {
      this.state.selectValue.splice(index, 1)
    } else {
      this.state.selectValue.push(value)
    }

    this.setState({})
  }

  handleCheckboxChange = (e) => {
    this.setState({
      checkboxValue: e.target.checked
    })
  }

  handleNumChange = (e) => {
    this.setState({
      numValue: e.target.value
    })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    console.log(this.fileRef.current.files[0].name)
  }

  render() {
    return (
      <>
        <div>
          <textarea value={this.state.value} onChange={this.handleTextareaChange} rows="10"></textarea>
        </div>
        <div>
          <select 
            value={this.state.selectValue}
            onChange={this.handleSelectChange}
            multiple
          >
            <option value="0">北京</option>
            <option value="1">深圳</option>
            <option value="2">上海</option>
          </select>
        </div>
        <div>
          {this.state.selectValue}
        </div>
        <div>
          <input 
            type="checkbox" 
            checked={this.state.checkboxValue}
            onChange={this.handleCheckboxChange}
          />

          <input 
            type="number"
            value={this.state.numValue}
            onChange={this.handleNumChange}
          />
        </div>

        {/* <div>
          <input type="text" value={this.state.value}/>
        </div> */}

        <div>
          <input type="text" defaultValue={this.state.value} ref={this.myRef}/>
        </div>

        <div>
          <form onSubmit={this.handleSubmit}>
            <input type="file" ref={this.fileRef}/>
            <input type="submit" value="submit"/>
          </form>
        </div>
      </>
    );
  }
}

export default Form;